package cn.com.hatech.cdkey.common.utils;


import cn.com.hatech.cdkey.common.constant.WebConst;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @projectName: hatech-blog
 * @package: cn.com.hatech.blog.common.utils
 * @className: Commons
 * @author: xuruikai
 * @description: 主题公共函数
 * @date: 2020/1/11 14:27
 * @version: 1.0
 */
@Component
public final class Commons {

    private static final String[] ICONS = {"bg-ico-book", "bg-ico-game", "bg-ico-note", "bg-ico-chat", "bg-ico-code", "bg-ico-image", "bg-ico-web", "bg-ico-link", "bg-ico-design", "bg-ico-lock"};

    private static Pattern m = Pattern.compile("src\\s*=\\s*\'?\"?(.*?)(\'|\"|>|\\s+)");

    /**
     * 判断分页中是否有数据
     *
     * @param paginator
     * @return
     */
    public static boolean isEmpty(Page paginator) {
        return paginator == null || (paginator.getRecords() == null) || (paginator.getRecords().size() == 0);
    }

    /**
     * 网站链接
     *
     * @return
     */
    public static String siteUrl() {
        return siteUrl("/");
    }

    /**
     * 返回网站链接下的全址
     *
     * @param sub 后面追加的地址
     * @return
     */
    public static String siteUrl(String sub) {
        return siteOption("siteUrl") + sub;
    }


    /**
     * 网站配置项
     *
     * @param key
     * @return
     */
    public static String siteOption(String key) {
        return siteOption(key, "");
    }

    /**
     * 网站配置项
     *
     * @param key
     * @param defaultValue 默认值
     * @return
     */
    public static String siteOption(String key, String defaultValue) {
        if (StringUtils.isEmpty(key)) {
            return "";
        }
        String str = WebConst.initConfig.get(key);
        if (StringUtils.isNotEmpty(str)) {
            return str;
        } else {
            return defaultValue;
        }
    }

    /**
     * 返回gravatar头像地址
     *
     * @param email
     * @return
     */
    public static String gravatar(String email) {
        String avatarUrl = "https://secure.gravatar.com/avatar";
        if (StringUtils.isEmpty(email)) {
            return avatarUrl;
        }
        String hash = TaleUtils.MD5Encode(email.trim().toLowerCase());
        return avatarUrl + "/" + hash;
    }

    /**
     * 获取随机数
     *
     * @param max
     * @param str
     * @return
     */
    public static String random(int max, String str) {
        return (new Random().nextInt(max - 1 + 1) + 1) + str;
    }

    /**
     * 返回文章链接地址
     *
     * @param cid
     * @return
     */
    public static String permalink(String cid) {
        return siteUrl("/article/" + cid);
    }

    /**
     * 博客首页文章显示分类
     *
     * @param categories
     * @return
     */
    public static String showCategories(String categories) throws UnsupportedEncodingException {
        if (StringUtils.isNotEmpty(categories)) {
            String[] arr = categories.split(",");
            StringBuffer sbuf = new StringBuffer();
            for (String c : arr) {
                sbuf.append("<a href=\"/category/" + URLEncoder.encode(c, "UTF-8") + "\">" + c + "</a>");
            }
            return sbuf.toString();
        }
        return showCategories("默认分类");
    }

    /**
     * 博客首页文章显示标签
     *
     * @param tags
     * @return
     */
    public static String showTags(String tags) throws UnsupportedEncodingException {
        if (StringUtils.isNotEmpty(tags)) {
            String[] arr = tags.split(",");
            StringBuffer sbuf = new StringBuffer();
            for (String c : arr) {
                sbuf.append("<a href=\"/tag/" + URLEncoder.encode(c, "UTF-8") + "\">" + c + "</a>");
            }
            return sbuf.toString();
        }
        return "";
    }

    /**
     * 显示文章内容，转换markdown为html
     *
     * @param value
     * @return
     */
    public static String article(String value) {
        if (StringUtils.isNotEmpty(value)) {
            value = value.replace("<!--more-->", "\r\n");
            return TaleUtils.mdToHtml(value);
        }
        return "";
    }

    /**
     * 显示文章缩略图，顺序为：文章第一张图 -> 随机获取
     *
     * @return
     */
    public static String showThumb(int cid) {
        int size = cid % 20;
        size = size == 0 ? 1 : size;
        return "/static/user/img/rand/" + size + ".jpg";
    }

    /**
     * 获取文章第一张图片
     *
     * @return
     */
    public static String showThumb(String content) {
        content = TaleUtils.mdToHtml(content);
        if (content.contains("<img")) {
            String img = "";
            String regExImg = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
            Pattern pImage = Pattern.compile(regExImg, Pattern.CASE_INSENSITIVE);
            Matcher mImage = pImage.matcher(content);
            if (mImage.find()) {
                img = img + "," + mImage.group();
                Matcher matcher = m.matcher(img);
                // //匹配src
                if (matcher.find()) {
                    return matcher.group(1);
                }
            }
        }
        return "";
    }

    /**
     * 显示文章图标
     *
     * @param cid
     * @return
     */
    public static String showIcon(int cid) {
        return ICONS[cid % ICONS.length];
    }

    /**
     * 获取社交的链接地址
     *
     * @return
     */
    public static Map<String, String> social() {
        final String prefix = "social_";
        Map<String, String> map = new HashMap<>(4);
        map.put("weibo", WebConst.initConfig.get(prefix + "weibo"));
        map.put("zhihu", WebConst.initConfig.get(prefix + "zhihu"));
        map.put("github", WebConst.initConfig.get(prefix + "github"));
        map.put("twitter", WebConst.initConfig.get(prefix + "twitter"));
        return map;
    }

}
